﻿using System;
using System.Linq;
using context;
using entities;

namespace DataAccessLibrary.DAL
{
    public class AuthenDAO
    {
        public string RoleGet(string account, string password)
        {
            using (var ctx = new BlueMDataContext())
            {
                return
                    ctx.Employees.First(p => p.EmployeeAccount == account && p.EmployeePassword == password).
                        EmployeePosition;
            }
        }

        public bool UserCheck(string account, string passwors, string position, string serviceName)
        {
            using (var ctx = new BlueMDataContext())
            {
                IQueryable<Employee> query =
                    ctx.Employees.Where(
                        p =>
                        p.EmployeeAccount == account && p.EmployeePassword == passwors &&
                        p.EmployeePosition == position);
                if (query.Any())
                {
                    var employeeLog = new EmployeeLog
                                          {
                                              EmployeeID = query.First().EmployeeID,
                                              LoginTime = DateTime.Now,
                                              ServiceName = serviceName
                                          };

                    ctx.EmployeeLogs.InsertOnSubmit(employeeLog);
                    ctx.SubmitChanges();
                    return true;
                }
                return false;
            }
        }

        public bool ChangePassword(string account, string password, string newPassword)
        {
            using (var ctx = new BlueMDataContext())
            {
                IQueryable<Employee> query =
                    ctx.Employees.Where(
                        p =>
                        p.EmployeeAccount == account && p.EmployeePassword == password);
                if (query.Count() == 1)
                {
                    Employee emp = query.First();
                    emp.EmployeePassword = newPassword;
                    ctx.SubmitChanges();
                    return true;
                }
                throw new Exception("Can not change password");
            }
        }

        public Employee SelectEmployee(string account, string password)
        {
            using (var ctx = new BlueMDataContext())
            {
                Employee employee =
                    ctx.Employees.First(p => p.EmployeeAccount == account && p.EmployeePassword == password);
                employee.EmployeePassword = "";
                return employee;
            }
        }
    }
}